//
//  ChooseCreditableCardVC.m
//  MRBang
//
//  Created by 铅笔 on 15/12/16.
//  Copyright © 2015年 杭州易网新科技. All rights reserved.
//

#import "ChooseCreditableCardVC.h"
#import "DetailChooseCreditVC.h"//每张卡的详情
#import "ApplyForACreditCardVC.h"//跳转到 银行那边
#import "LoginViewController.h"//登录页面
#import "FillInInformationVC.h"//立即申请 进入的页面

#import "ChooseCreditableCardModel.h"
#import "HelpMeDoModel.h"

#import "ChooseCreditableCardCell.h"
#import "PopChooseBankCardVIew.h"

@interface ChooseCreditableCardVC ()<UITableViewDataSource,UITableViewDelegate,ImmediateApplicationDelegate,chooseOneBankCardActionDelegate>
{
    UIView *view_topChoseBackGround;//头部背景 视图
    PopChooseBankCardVIew *popView;//弹出的视图
    UIView *view_cover;//遮盖视图
//    UILabel *label_nameTitle;//头部 选择的银行卡信息替换
    
    NSString * isNoNameTitle;
}

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *mutableArray_data;//存放所有数据

@end

@implementation ChooseCreditableCardVC

- (NSMutableArray *)mutableArray_data
{
    if (!_mutableArray_data) {
        _mutableArray_data = [[NSMutableArray alloc] init];
    }
    return _mutableArray_data;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
     self.title = @"帮我办";
    
    [self.mutableArray_data removeAllObjects];
    
    isNoNameTitle = @"nono";
    [self initWithRightButtonSubviews];
    
    //创建子视图
    [self initWithAllSubviews];
    
    //网络数据请求
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self DataSourceRequestListCreditcardView];
    
    [self setUprefresh];
}


#pragma mark --- right button
- (void) initWithRightButtonSubviews
{
    UIButton *button_rightChange = [UIButton buttonWithType:UIButtonTypeCustom];
    [button_rightChange setTitle:@"返回首页"  forState:UIControlStateNormal];
    [button_rightChange setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    button_rightChange.frame = CGRectMake(15, 0, 60, 30);
    [button_rightChange.titleLabel setFont:[UIFont systemFontOfSize:24*PROPORTION_WIDTH]];
    
    UIBarButtonItem *menuButton = [[UIBarButtonItem alloc] initWithCustomView:button_rightChange];
    self.navigationItem.rightBarButtonItem = menuButton;
    
    [button_rightChange addTarget:self action:@selector(backToHomeViewAction)
                 forControlEvents:UIControlEventTouchUpInside];
    
}

//返回到首页
- (void) backToHomeViewAction
{
    [self.tabBarController setSelectedIndex:0];
    [self.navigationController popToRootViewControllerAnimated:YES];
    
}

#pragma mark - 集成下拉刷洗 上拉加载
- (void)setUprefresh
{
    __weak __typeof(self) weakSelf = self;
    
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [weakSelf loadNewData];
    }];
    
    // 马上进入刷新状态
    //    [self.tableView.header beginRefreshing];
}

#pragma mark - 数据处理相关
#pragma mark 下拉刷新数据
- (void)loadNewData
{
    // 1.添加假数据
    [self.mutableArray_data removeAllObjects];
    [self DataSourceRequestListCreditcardView];
    
    [self.tableView.header endRefreshing];
}

#pragma mark ---- 创建子视图
- (void) initWithAllSubviews
{
    
    //tableView
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    [self.view addSubview:self.tableView];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.showsVerticalScrollIndicator = NO;
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    //    self.tableView.bounces = NO;
    
}

#pragma mark --- UITableViewDataSource
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.mutableArray_data.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ID = @"cellChooseCreditableCard";
    ChooseCreditableCardCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    
    if (cell == nil) {
        cell = [[ChooseCreditableCardCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    cell.immediateDelegate = self;
    
    if (self.mutableArray_data.count!=0) {
        cell.model_choseCredita = self.mutableArray_data[indexPath.row];
    }
    
    return cell;
}

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.mutableArray_data.count!=0) {
        ChooseCreditableCardModel *model_cardid = self.mutableArray_data[indexPath.row];
        
        //存储 creditcardcardid
        [[NSUserDefaults standardUserDefaults] setObject:model_cardid.creditcardcardid forKey:@"creditcardcardid"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        DetailChooseCreditVC *detailVC = [[DetailChooseCreditVC alloc] init];
        detailVC.str_cardID = model_cardid.cardid;
        detailVC.model_creadit = model_cardid;
        
        [self.navigationController pushViewController:detailVC animated:NO];
    }
}

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view_header = [[UIView alloc] init];
    
    view_header.backgroundColor = COLOR_EVERYVIEWBG;
    
    UIButton *button_popViewchoose = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 70*PROPORTION_WIDTH)];
    [view_header addSubview:button_popViewchoose];
    button_popViewchoose.backgroundColor = [UIColor whiteColor];
    
    //label
    UILabel *label_nameTitle = [[UILabel alloc] initWithFrame:CGRectMake(0, 20*PROPORTION_WIDTH, 434*PROPORTION_WIDTH, 34*PROPORTION_WIDTH)];
    [button_popViewchoose addSubview:label_nameTitle];
    label_nameTitle.font = [UIFont systemFontOfSize:Font_SIZE_30];
    label_nameTitle.textColor = [BaseViewController colorWithHexString:@"#010101"];
    label_nameTitle.textAlignment = NSTextAlignmentRight;
    
    if ([isNoNameTitle isEqualToString:@"nono"]) {
        
        label_nameTitle.text = self.str_bankName;
    }
    else
    {
        label_nameTitle.text = isNoNameTitle;
    }
    //imageView
    UIImageView *imageView_down = [[UIImageView alloc] initWithFrame:CGRectMake(label_nameTitle.right+15*PROPORTION_WIDTH, 17*PROPORTION_WIDTH, 40*PROPORTION_WIDTH, 35*PROPORTION_WIDTH)];
    [button_popViewchoose addSubview:imageView_down];
    imageView_down.image = [UIImage imageNamed:@"downarrow"];
    
    //button
    [button_popViewchoose addTarget:self action:@selector(popViewShowChoseContentAction) forControlEvents:UIControlEventTouchUpInside];
    return view_header;
}

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 281*PROPORTION_WIDTH;
}

- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{

    return 90*PROPORTION_WIDTH;

}

#pragma mark --- 展示 选择的 视图
- (void) popViewShowChoseContentAction
{
    view_cover = [[UIView alloc] initWithFrame:self.view.frame];
    [self.view addSubview:view_cover];
    view_cover.backgroundColor = [UIColor blackColor];
    view_cover.alpha = 0.6;
    
    //gesture
    UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removeViewsFromSubview)];
    [view_cover addGestureRecognizer:gesture];
    
    //popview
    popView = [[PopChooseBankCardVIew alloc] initWithFrame:CGRectMake(160*PROPORTION_WIDTH,64+82*PROPORTION_WIDTH, kScreenWidth-2*160*PROPORTION_WIDTH, 200)];
    popView.mutableArray_allModel = self.mutableArray_pathDatas;
    [self.view addSubview:popView];
    popView.choseBankDelegate = self;
}

#pragma mark --- 立即申请
- (void) ImmediateApplication:(ChooseCreditableCardModel *)model_card
{
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"memberid"])
    {
        if ([model_card.cardid containsString:@"https://"]) {
            ApplyForACreditCardVC *applyForView = [[ApplyForACreditCardVC alloc] init];
            applyForView.str_lianjie = model_card.cardid;
            [self.navigationController pushViewController:applyForView animated:YES];
        }
        else
        {
            //存储 creditcardcardid
            [[NSUserDefaults standardUserDefaults] setObject:model_card.creditcardcardid forKey:@"creditcardcardid"];
            [[NSUserDefaults standardUserDefaults] synchronize];

            FillInInformationVC *fillInView = [[FillInInformationVC alloc] init];
            [self.navigationController pushViewController:fillInView animated:YES];
        }
    }
    else
    {
        LoginViewController *longin = [[LoginViewController alloc] init];
        longin.fromeWhere = @"chooseCredit";
        [self.navigationController pushViewController:longin animated:YES];
    }
}

#pragma mark --- chooseOneBankCardActionDelegate
- (void) chooseOneBankCardAction:(HelpMeDoModel *)model_help
{
    [self.mutableArray_data removeAllObjects];
    
    self.str_creditcardbankid = model_help.creditcardbankid;
    isNoNameTitle = model_help.name;

    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    //网络请求
    [self DataSourceRequestListCreditcardView];
   
    [view_cover removeFromSuperview];
    [popView removeFromSuperview];
}

- (void) removeViewsFromSubview
{
    [view_cover removeFromSuperview];
    [popView removeFromSuperview];
}

#pragma mark -- 网络数据请求
- (void) DataSourceRequestListCreditcardView
{
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    NetworkStatus status = [reach currentReachabilityStatus];
    
    if (![UIView NetFromStatus:status]) {
      
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];

        [UIView showAlertMsg:@"网络连接已断开" andShowBgColor:[UIColor blackColor] andLabelTectColor:[UIColor whiteColor]];
        
        return;
    }
    else
    {
        NSString *strUrl = [NSString stringWithFormat:@"%@creditcard/card/get",MRAPI];
        
        NSDictionary *paras_list = @{@"creditcardbankid":self.str_creditcardbankid};
        
        [[HttpRequest shardWebUtil] getNetworkRequestURLString:strUrl parameters:paras_list success:^(id obj) {
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
            
            NSString *str_false = obj[@"error"];
            
            if (str_false.length==0) {
                NSArray *array_data = obj[@"data"];
                if (array_data.count!=0) {
                    for (int i=0; i<array_data.count; i++) {
                        ChooseCreditableCardModel *model = [[ChooseCreditableCardModel alloc] init];
                        [model decodeDic:array_data[i]];
                        [self.mutableArray_data addObject:model];
                    }
                }
                else
                {
                    [BaseViewController showMessage:@"暂无数据"];
                }
                
                [self.tableView reloadData];
            }
            else
            {
                [BaseViewController showMessage:str_false];
            }
            
        } fail:^(NSError *error) {
            [BaseViewController showMessage:@"请求超时"];
            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        }];

    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

@end
